<?php


namespace app\common\model;


use app\common\business\Patient;
use app\common\lib\ZhyxMongo;
use catcher\base\CatchRequest;
use catcher\exceptions\FailedException;
use MongoDB\BSON\ObjectId;

class DiseasePatientTaskDetail extends BaseModel
{
    protected $name = "disease_patient_task_detail";

    public function modifyStatus(string $outerId, int $type = 1, string $historyId = ""): bool
    {
        $condition = ["outer_id", "=", $outerId];
        $saveData = [
            'latest_status' => 2
        ];
        if ($type === 2) {
            $condition = ["id", "=", $outerId];
            $saveData["outer_id"] = $historyId ?? "";
        }
        $taskDetail = $this->where([$condition])->find();

        if (isset($taskDetail) && !empty($taskDetail)) {
            # 标记成已完成
            if ($taskDetail["latest_status"] !== 2) {
                $result = $taskDetail->save($saveData);
                if ($result !== false) {
                    # 判断该步骤是否有未完成的状态
                    $undoneCount = $this->where([["latest_status", "<>", 2], ["task_id", "=", $taskDetail["task_id"]]])->count();
                    if ($undoneCount == 0) {
                        # 执行外层状态的修改
                        (new DiseasePatientTask())->where([["planList.plan_task_id", "=", $taskDetail["task_id"]]])->save([
                            'planList.$.plan_task_status' => 2,
                            'update_at' => time()
                        ]);
                    }
                }
            }
            return true;
        }
        throw new FailedException("外部关联Id不存在");
    }

    public function getProcessList(string $taskId): array
    {
        $collection = ZhyxMongo::getInstance()->setCollection('disease_patient_task_detail');

        //$cursor = $collection->aggregate([['$match' => ['task_id' => new ObjectId($taskId), 'deleted_at' => 0]], ['$group' => ['_id' => '$task_type', 'types' => ['$first' => '$task_type'], 'task_name' => ['$addToSet' => '$task_name'], 'colspan' => ['$sum' => 1], 'details' => ['$addToSet' => ['content' => ['$switch' => ['branches' => [['case' => ['$in' => ['$task_type', ['tel', 'others']]], 'then' => '$task_name']], 'default' => '$attachment_title']], 'details_id' => '$_id', 'latest_status' => '$latest_status', 'latest_status_text' => ['$switch' => ['branches' => [['case' => ['$eq' => ['$latest_status', -1]], 'then' => '待开启'], ['case' => ['$eq' => ['$latest_status', 0]], 'then' => '未开始'], ['case' => ['$eq' => ['$latest_status', 1]], 'then' => '进行中'], ['case' => ['$eq' => ['$latest_status', 2]], 'then' => '已完成'], ['case' => ['$eq' => ['$latest_status', 3]], 'then' => '已终止']], 'default' => '待开启']], 'attachment_title' => '$attachment_title', 'attachment_value' => '$attachment_value']]]], ['$project' => ['_id' => false]], ['$addFields' => ['types' => ['$switch' => ['branches' => [['case' => ['$eq' => ['$types', 'tel']], 'then' => '电话随访'], ['case' => ['$eq' => ['$types', 'form']], 'then' => '表单随访'], ['case' => ['$eq' => ['$types', 'content']], 'then' => '宣教'], ['case' => ['$eq' => ['$types', 'plan']], 'then' => '复诊计划']], 'default' => '其它']]]]]);
        $cursor = $collection->aggregate([['$match' => ['task_id' => new ObjectId($taskId), 'deleted_at' => 0]], ['$group' => ['_id' => ['task_type' => '$task_type', 'task_name' => '$task_name'], 'types' => ['$first' => '$task_type'], 'task_name' => ['$first' => '$task_name'], 'colspan' => ['$sum' => 1], 'details' => ['$addToSet' => ['content' => ['$switch' => ['branches' => [['case' => ['$in' => ['$task_type', ['tel', 'others']]], 'then' => '$task_name']], 'default' => '$attachment_title']], 'details_id' => '$_id', 'latest_status' => '$latest_status', 'latest_status_text' => ['$switch' => ['branches' => [['case' => ['$eq' => ['$latest_status', -1]], 'then' => '待开启'], ['case' => ['$eq' => ['$latest_status', 0]], 'then' => '未开始'], ['case' => ['$eq' => ['$latest_status', 1]], 'then' => '进行中'], ['case' => ['$eq' => ['$latest_status', 2]], 'then' => '已完成'], ['case' => ['$eq' => ['$latest_status', 3]], 'then' => '已终止']], 'default' => '待开启']], 'attachment_title' => '$attachment_title', 'attachment_value' => '$attachment_value']]]], ['$group' => ['_id' => '$types', 'types' => ['$first' => '$types'], 'details' => ['$addToSet' => '$$ROOT']]], ['$project' => ['_id' => false]], ['$addFields' => ['colspans' => ['$sum' => '$details.colspan'], 'types' => ['$switch' => ['branches' => [['case' => ['$eq' => ['$types', 'tel']], 'then' => '电话咨询'], ['case' => ['$eq' => ['$types', 'form']], 'then' => '调查表'], ['case' => ['$eq' => ['$types', 'content']], 'then' => '患教文章'], ['case' => ['$eq' => ['$types', 'plan']], 'then' => '复诊提醒']], 'default' => '其它']]]]]);

        return iterator_to_array($cursor);
    }

    public function getPatientByTaskId(string $taskId): array
    {

        $taskInfo = (new DiseasePatientTaskDetail())->where([["task_id", "=", new ObjectId($taskId)]])->find();
        #根据患者id获取患者长id，患者手机号信息
        $patientInfo = (new PatientInfo())->getPatientInfo($taskInfo["patient_id"]);
        if (!empty($patientInfo)) {
            return [
                "telephone" => $patientInfo["presentTelphone"],
                "patientId" => $taskInfo["patient_id"],
                "patient_uuid" => $patientInfo["id"]
            ];
        }
        return [];
    }

    public function getListByDiseaseId(string $diseaseId): array
    {
        $arr = ["day" => "日", "week" => "周", "month" => "月", "year" => "年"];
        #状态  -1 未开启 0待进行 1进行中 2已完成 3已过期
        $statusArr = [0 => "待进行", 1 => "进行中", 2 => "已完成", 3 => "已过期", 4 => "中止"];
        $collection = ZhyxMongo::getInstance()->setCollection('disease_patient_task');
        $cursor = $collection->aggregate([['$match' => ['bind_id' => new ObjectId($diseaseId), 'deleted_at' => 0]], ['$project' => ['remark' => true, 'step_order' => true, 'step_is_repeat' => true, 'step_start_value' => true, 'step_repeat_value' => true, 'step_repeat_type' => true, 'step_start_type' => true, 'plan_start_date' => ['$arrayElemAt' => ['$planList.plan_date', 0]], 'plan_task_status' => ['$arrayElemAt' => ['$planList.plan_task_status', 0]], 'step_detail' => '$step_detail.task_name', 'step_type' => '$step_type.name']], ['$sort' => ['step_order' => 1]]]);
        $result = iterator_to_array($cursor);
        if (!empty($result)) {
            foreach ($result as $k => &$v) {
                $v["corner_mark"] = $v["step_is_repeat"] === true ? "周期" . $v["step_repeat_value"] . $arr[$v["step_repeat_type"]] : "";
                $v["step_type"] .= $v["step_start_value"] . $arr[$v["step_start_type"]];
                $v["plan_task_status_text"] = $statusArr[$v["plan_task_status"]];
            }
        }
        return $result;
    }

    public function getSchemeDetailsByTaskId(string $taskId): array
    {
        $collection = ZhyxMongo::getInstance()->setCollection('disease_patient_task_detail');
        $cursor = $collection->aggregate([['$match' => ['task_main_id' => $taskId, 'deleted_at' => 0]], ['$group' => ['_id' => '$task_id', 'creator_by' => ['$first' => '$creator_by'], 'task_date' => ['$first' => '$task_start_date'], 'details' => ['$push' => ['content' => ['$switch' => ['branches' => [['case' => ['$in' => ['$task_type', ['tel', 'others', 'plan']]], 'then' => '$task_name']], 'default' => '$attachment_title']], 'attachment_value' => '$attachment_value', 'latest_status' => '$latest_status', 'creator_by' => '$creator_by', 'latest_status_text' => ['$switch' => ['branches' => [['case' => ['$eq' => ['$latest_status', -1]], 'then' => '待开启'], ['case' => ['$eq' => ['$latest_status', 0]], 'then' => '未开始'], ['case' => ['$eq' => ['$latest_status', 1]], 'then' => '进行中'], ['case' => ['$eq' => ['$latest_status', 2]], 'then' => '已完成'], ['case' => ['$eq' => ['$latest_status', 3]], 'then' => '已过期'], ['case' => ['$eq' => ['$latest_status', 4]], 'then' => '中止']], 'default' => '待开启']]]]]], ['$sort' => ['_id' => 1]]]);
        return iterator_to_array($cursor);
    }

    public function getLatestTask(string $patientId)
    {
        $arr = ["content" => "宣教文章", "form" => "调查表", "tel" => "语音咨询", "plan" => "复诊提醒", "others" => "其它"];
        # 根据患者id获取最新一个随访步骤
        $bindArr = (new BindDiseasePath())->where([["patient_id", "=", $patientId], ["is_close", "=", 0], ["deleted_at", "=", 0]])->field(["id", "step"])->select();

        if (!empty($bindArr)) {
            $bindArr = $bindArr->toArray();
            foreach ($bindArr as $k => $v) {

                $collection = ZhyxMongo::getInstance()->setCollection('disease_patient_task');
                $taskInfo = iterator_to_array($collection->aggregate([['$match' => ['bind_id' => new ObjectId($v["id"]), 'step_order' => ['$gte' => $v["step"]]]], ['$unwind' => ['path' => '$planList', 'preserveNullAndEmptyArrays' => false]], ['$match' => ['planList.plan_task_status' => 0]], ['$sort' => ['planList.update_at' => -1]], ['$project' => ['task_id' => '$planList.plan_task_id', "path_name" => '$disease_name', 'plan_date' => '$planList.plan_date']], ['$limit' => 1]]));
                if (!empty($taskInfo)) {
                    $taskId = (string)$taskInfo[0]["task_id"];
                    $collection = ZhyxMongo::getInstance()->setCollection('disease_patient_task_detail');
                    $cursor = $collection->aggregate([['$match' => ['task_id' => new ObjectId($taskId), 'deleted_at' => 0]], ['$group' => ['_id' => '$task_type', 'count' => ['$sum' => 1], 'finish_count' => ['$sum' => ['$cond' => ['if' => ['$eq' => ['$latest_status', 2]], 'then' => 1, 'else' => 0]]], 'detail' => ['$push' => ['content' => ['$cond' => ['if' => ['$in' => ['$task_type', ['tel', 'plan', 'others']]], 'then' => '$task_name', 'else' => '$attachment_title']], 'ed_id' => '$attachment_value', 'latest_status' => '$latest_status', 'latest_status_text' => ['$switch' => ['branches' => [['case' => ['$eq' => ['$latest_status', -1]], 'then' => '待开启'], ['case' => ['$eq' => ['$latest_status', 0]], 'then' => '未开始'], ['case' => ['$eq' => ['$latest_status', 1]], 'then' => '进行中'], ['case' => ['$eq' => ['$latest_status', 2]], 'then' => '已完成'], ['case' => ['$eq' => ['$latest_status', 3]], 'then' => '已终止']], 'default' => '待开启']]]]]], ['$group' => ['_id' => null, 'count' => ['$sum' => '$count'], 'finish_count' => ['$sum' => '$finish_count'], 'details' => ['$push' => '$$ROOT']]]]);
                    $result = iterator_to_array($cursor);
                    if (!empty($result)) {
                        $result = $result[0];
                        $result["task_id"] = $taskId;
                        foreach ($result["details"] as $kk => &$vv) {
                            $vv["type"] = $arr[$vv["_id"]];
                        }
                        $result["path_name"] = $taskInfo[0]["path_name"] ?? "";
                        $result["plan_date"] = $taskInfo[0]["plan_date"] ?? "";

                    }
                    $bindArr[$k] = $result;
                } else {
                    unset($bindArr[$k]);
                }
            }
        }
        return $bindArr;
    }


}